
//新版基础函数
var f = {
    init:function() {
        log("程序初始化成功")
    },
    //post
    post : function(url,data){
        var res = http.post(url, data);
        var data = res.body.string();
        if(data){
            // log(data);
            return data;
        }
    },
    //get
    get : function(url){
        var res = http.get(url);
        var data = res.body.string();
        if(data){
            return data;
        }
    },
    //读取本地数据
    getLocal:function ( name, key) {
        const storage = storages.create(name);  //创建storage对象
        if (storage.contains(key)) {
            return storage.get(key);
        };
        //默认返回undefined
    },
    //基础函数
    active:function(pkg,n){
        if(!n){n=5}
        if(  currentPackage() == pkg ){
            log("应用在前端");
            return true;
        }else{
            log("启动一次应用");
            app.launch(pkg);
            sleep(1000)
            f.ms({"textMatches":"允许|始终允许"},true)
            sleep(1000*n)
        }
    },
    //准备点击
    click:function (x,y,sleeptime,name){
        if ( ! sleeptime ){sleeptime = 1}
        if ( name ){
            log('准备点击->'+name,"x:",x,"y:",y);
        }else{
            log('准备点击坐标->', "x:",x,"y:",y);
        }
        if( x > 0  && y > 0  ){
            threads.start(function(){
                //在新线程执行的代码
                click(x,y);
            });
            // click(x,y);
            sleep(sleeptime*1000);
            return true
        }else{
            log('坐标错误');
        }
    },
    //点击obj
    clickObj:function (obj,sleeptime,name){
        if ( ! sleeptime ){ sleeptime == 1 } 
        log(  name ? ("准备点击对象->" + name) : "点击未命名对象" )
        x = obj.bounds().centerX()
        y = obj.bounds().centerY()
        return f.click(x,y,sleeptime,name)
    },
    //穿透点击
    clickTrue:function(obj,sleeptime,name,lun){
        sleeptime ? sleeptime : 1
        let result = false;
        lun ? lun : 3
        for (let i=0;i<lun;i++){
            if (  obj && obj.clickable() ){
                obj.click();
                log(  name ? ("准备穿透点击对象->" + name) : "准备穿透点击未命名对象" )
                result = true
                break
            }
            obj = obj.parent()
        }
        if ( result ) { sleep(sleeptime * 1000) }
        return result
    },
    //正则点击
    ms:function (obj,clicks,sleeptimes,name,findtime,lun){
        if (!sleeptimes) { sleeptimes = 1}
        if (!findtime) { findtime = 200}
        if (!lun) { lun = 3}

        var txt = '';
        for(let key in obj){
            if ( key.search("Matches") > 0 ){
                eval("var matches = /" + obj[key] + "/")
                txt = txt + key+'('+matches+').'
            }else if( key ==  'boundsInside' ){
                txt = txt + key+'('+obj[key]+').'
            }else{
                txt = txt + key+'("'+obj[key]+'").'
            }
        }
        var txt = "let objs = "+txt+"findOne("+findtime+");"
        log(txt)
        eval(txt)
        if ( objs ) {
            log( '找到==>' + objs.text() || objs.desc() || objs.id() || objs.className() )
            if ( clicks ){
                name = obj['textMatches'] || obj['descMatches'] || obj['idMatches'] || obj['text'] || obj['desc'] || obj['id']
                if (lun < 1 || !f.clickTrue( objs,sleeptimes,name,lun )){
                    log('准备坐标点击')
                    return f.clickObj( objs,sleeptimes,name );
                }
            }
            return true;
        }
    },
    rd:function (min,max){
        if (min<=max){
            return random(min,max)
        }else{
            return random(max,min)
        }
    },
    moveTo:function (percentX, percentY, percentX1, percentY1, times) {
        // 获取设备的宽度和高度
        const width = device.width;
        const height = device.height;

        // 将百分比转换为实际坐标
        const x = Math.round(width * percentX);
        const y = Math.round(height * percentY);
        const x1 = Math.round(width * percentX1);
        const y1 = Math.round(height * percentY1);

        // 执行滑动操作
        swipe(x, y, x1, y1, times);
        sleep(1000);
    }
}
f.init()

var width = 720;
var height = 1440;
var width = device.width;
var height = device.height;
var phoneMode = device.brand;

log([currentPackage(),currentActivity(),width,height]);

// 新增一个 post 方法，请求头为 json 格式，只需要传入 data 参数
f.postJson = function(data) {
    let url = 'https://api.wenfree.cn/?s=App.Autojs_Tiktok.Spiders_comment'
    var headers = {
        "Content-Type": "application/json"
    };
    log(url,JSON.stringify(data))
    var res = http.postJson(url, data, headers);
    var data = res.body.string();
    if(data){
        log(data);
        return data;
    }
};


function getTitleConent(){
    if ( currentActivity() == "com.wudaokou.hippo.search.SearchActivity" ){
        log("进入搜索界面")
        //没有分类就返回
        if ( !appInfo.category){
            return true;
        }

        try {
            appInfo['search_key'] = id("tv_search_editable_keyword").findOne(200).text()

            let allprice = textMatches("¥.*").find();
            // log(allprice[0].text())
            for (let i=0;i<allprice.length;i++){
                let price = allprice[i].text()
                
                // 假设 allprice[i] 是当前元素，获取其兄弟节点的 text 内容作为 title
                function getTitle(objects){
                    let siblings = objects.parent().children();
                    let title = '';
                    for (let j = 0; j < siblings.length; j++) {
                        let siblingText = siblings[j].text();
                        if (siblingText.length > 6) {
                            title += siblingText + ' ';
                            return title.trim();
                        }
                    }
                }
                let title = getTitle(allprice[i]);
                log(title, price)
        
                var postData = {
                    "city": "北京",
                    "local": appInfo.local,
                    "category": appInfo.category,
                    "category2": appInfo.category2,
                    "search_key": appInfo['search_key'],
                    "title": title,
                };
                
                if (price.includes('/')) {
                    postData['price'] = price;
                } else {
                    postData['vip'] = price;
                }
                f.postJson(postData)
            }
        }catch (error) {
            log('获取标题内容失败', error);
        }
        
        if (f.ms({"textMatches":"还有.*个已售完商品"}, true ) ){
            //这里要把这个点开
        }else
        if( f.ms({"textMatches":"我可是有底线的哦||正在加载更多||RECOMMEND"}) ){
            return true
        }
    
        f.moveTo(0.5,0.8,0.5,0.5,1000)
    }
}





// if (getTitleConent()) {
//     back();
// }

var appInfo = {
    search_word: '',
    shop: '',
    categories: '',
    name: '',
    price: '',
    price_old: '',
    author: '',
    rate: '',
    sold: '',
    mintitle: '',
    alltitle: '',
    rank: '',
    link: '',
    fav: '',
    tag: '',
}
var storage = storages.create("tiktok");
var look = []
look = storage.get("look") || [];
// storage.remove("look");
log(look)

f.active("com.zhiliaoapp.musically", 5)
//批查打印app参数
function printAll(ways) {
    if (!ways) {
        ways = 'className'
    }
    if (ways = 'className') {
        var all_Info = classNameMatches(/.*/).find();
    } else
        if (ways == 'text') {
            var all_Info = textMatches(/.*/).find();
        } else
            if (ways == 'id') {
                var all_Info = idMatches(/.*/).find();
            } else {
                eval('var all_Info = ' + ways + '.find();')
            }

    if (all_Info) {
        for (var i = 0; i < all_Info.length; i++) {
            var d = all_Info[i];
            log(i, d.id(), d.text(), "描述:" + d.desc(), '"类名":"' + d.className() + '"', "深度->" + d.depth(),
                d.bounds().centerX(), d.bounds().centerY())
        }
    } else {
        log('没有找到任何相关的节点')
    }
}

function getAllText(obj){
    const textInfo = {};
    try {
        if( obj.text() ){
            textInfo['text'] = obj.text()
        }
        if( obj.desc() ){
            textInfo['desc'] = obj.desc()
        }
        if( obj.id() ){
            textInfo['id'] = obj.id()
        }
        if( obj.children().length > 0 ){
            for (let i=0;i<obj.children().length;i++){
                let child = obj.children()[i]
                textInfo[i] = getAllText(child)
            }
        }
    } catch (error) {
        
    }
    return textInfo;
}

var used_price = []



// printAll()

// if ( f.ms({ "textMatches": ".*reviews.*", id: 'title' } ) ){ 
//     log('在评论界面')
// }



function getComment() {
    var info = {};

    // var seeMore = textMatches(".*See more").findOne(200);
    // if (seeMore) {
    //     log("找到 See more 元素");
    //     // 执行点击操作
    //     f.click( seeMore.bounds().right-50, seeMore.bounds().bottom-10, 1, '点击 See more' );
    // }

    f.ms({ "textMatches": "See more", }, true, 1, '点击 See more' );

    //评论区
    var obj = id("dan").find();
    if (obj) {
        info.commnet = [];
        log("找到 dan 元素");
        for (let i = 0; i < obj.length; i++) {
            // log(obj[i].text())
            info.commnet.push(obj[i].text());
        }
    }
    //nickname
    var obj = id("com.zhiliaoapp.musically:id/ug8").find();
    if (obj) {
        log("找到 nickname 元素");
        info.nickname = [];
        for (let i = 0; i < obj.length; i++) {
            log(obj[i].text());
            info.nickname.push(obj[i].text());
        }
    }
    //item
    var obj = id("com.zhiliaoapp.musically:id/q3m").find();
    if (obj) {
        info.item = [];
        log("找到 item 元素");
        for (let i = 0; i < obj.length; i++) {
            log(obj[i].text());
            info.item.push(obj[i].text());
        }
    }

    //产品
    var obj = id("com.zhiliaoapp.musically:id/n78").find();
    if (obj) {
        info.pruduct = [];
        log("找到 产品 元素");
        for (let i = 0; i < obj.length; i++) {
            log(obj[i].text());
            info.pruduct.push(obj[i].text());
        }
    }

    log(info);
    for (let i = 0; i < info.commnet.length; i++) {
        f.postJson({
            shop: appInfo.shop,
            content: info.commnet[i],
            nickname: info.nickname[i],
            item: info.item[i],
            pruduct: info.pruduct[i],
        });
    }
    return true
}


while (true) {
    try {
        var shopname = id('tgc').findOne(200).text();
        appInfo.shop = shopname;
        log('店铺名称:', shopname);
        f.ms( { "textMatches": "Customer.*", id: 'pwr' }, true, 1, '点击 评论' );
    } catch (error) {
        
    }
    if( appInfo.shop ){
        if(getComment()){
            f.moveTo(0.5,0.8,0.5,0.5,1000)
        }
    }else{
        back()
        sleep(1000*5);
    }
}



